package com.zygh.lz.controller.pc;

import cn.hutool.core.img.Img;
import cn.hutool.core.io.FileUtil;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zygh.lz.dao.EquipageMapper;
import com.zygh.lz.dao.SectionMapper;
import com.zygh.lz.dao.SheetMapper;
import com.zygh.lz.dao.StaffMapper;
import com.zygh.lz.entity.Equipage;
import com.zygh.lz.entity.Section;
import com.zygh.lz.entity.Sheet;
import com.zygh.lz.entity.Staff;
import com.zygh.lz.stapprove.SysPcLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/ExcelReader")
@Api(tags = "录入民警信息")
public class ExcelReader {

    @Value("${file.upload}")
    private String uploadDir;
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");

    @Resource
    private StaffMapper staffMapper;
    @Resource
    private SheetMapper sheetMapper;

    @Resource
    private EquipageMapper equipageMapper;
    @Resource
    private SectionMapper sectionMapper;


    //民警
    @ApiOperation("读取Excel表格图片数据，插入到数据库中")
    @GetMapping("ReadExcels")
    public void ReadExcels() throws IOException {
        cn.hutool.poi.excel.ExcelReader reader = ExcelUtil.getReader("C:/Users/ms/Desktop/文档录/道路勤务资料/数据导出2021.12.28.xls");
        Workbook workbook = reader.getWorkbook();
        List<? extends PictureData> pictures = workbook.getAllPictures();
        List<Map<String, Object>> readAll = reader.readAll();

        for (int i = 0; i < readAll.size(); i++) {
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String tempFileName = System.currentTimeMillis() + uuid + ".jpg";
            Date date = new Date();
            String format = simpleDateFormat.format(date.getTime());
            String imgFilePath = "D:/dlqw/picture/" + format + "/" + tempFileName;//新生成的图片
            byte[] data = pictures.get(i).getData();
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(data);
            out.flush();
            out.close();
            Staff staff = new Staff();
            staff.setStaffNum(readAll.get(i).get("警号").toString());
            staff.setStaffPhoto(format + "/" + tempFileName);
            staffMapper.updateInfo(staff);

        }
    }

    //辅警
    @ApiOperation("读取文件夹里及子目录里所有图片数据，插入到数据库中")
    @GetMapping("ReadFille")
    public void ReadFille(String path) throws IOException {
        // 获得指定文件对象
        getFile(path, 0);
    }

//    public static void main(String[] args) throws IOException {
//        ExcelReader excelReader = new ExcelReader();
//        excelReader.getFile("D:\\dlqw\\picture\\20220224", 0);
//    }


    private void getFile(String path, int deep) throws IOException {
        // 获得指定文件对象
        File file = new File(path);
        // 获得该文件夹内的所有文件
        File[] array = file.listFiles();

        for (int i = 0; i < array.length; i++) {
            if (array[i].isFile())//如果是文件
            {
                //System.out.println(array[i].getPath());
                //========================图片新路径========================
                // String path1 = array[i].getPath();
//                File parentFile = array[i].getParentFile();
//                String parent1 = parentFile.getParent();
//                String parent = array[i].getParent();


                String name = array[i].getName();
                //String ID = name.substring(0, name.indexOf("."));
                //数据库里没有这个身份证号在做
                //Staff staffByID = staffMapper.findStaffByID(ID);
                //if (staffByID != null && StringUtils.isEmpty(staffByID.getStaffPhoto())) {
                //String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                //String fileType = name.substring(name.lastIndexOf(".") + 1, name.length()).toLowerCase();
                //String tempFileName = System.currentTimeMillis() + uuid + "." + fileType;
                //Date date = new Date();
                //String format = simpleDateFormat.format(date.getTime());
                //String picUrl = "D:/dlqw/picture/" + array[i] + File.separator + name;//新生成的图片
                String suffixName = name.substring(name.lastIndexOf('.'));
                if (".jpg".equals(suffixName)) {
                    System.out.println(array[i].getPath());
                    Img.from(FileUtil.file(array[i].getPath()))
                            .setQuality(0.8)//压缩比率
                            .write(FileUtil.file(array[i].getPath()));
                }


//                FileInputStream in = new FileInputStream(new File(array[i].toString()));// 指定要读取的图片
//                FileOutputStream out = new FileOutputStream(new File(picUrl));// 指定要写入的图片
//                int n = 0;// 每次读取的字节长度
//                byte[] bb = new byte[1024];// 存储每次读取的内容
//                while ((n = in.read(bb)) != -1) {
//                    out.write(bb, 0, n);// 将读取的内容，写入到输出流当中
//                }
//                out.close();// 关闭输入输出流
//                in.close();

//
//                    Staff staff = new Staff();
//                    staff.setStaffPhoto(format + "/" + tempFileName);
//                    staff.setIdentification(ID);
//                    System.out.println("<<<<<<" + ID);
//                    staffMapper.updateInfo(staff);
                //  }

                // 输出当前文件的完整路径
                // System.out.println("#####" + array[i]);
                // 同样输出当前文件的完整路径   大家可以去掉注释 测试一下
                // System.out.println(array[i].getPath());
            } else if (array[i].isDirectory())//如果是文件夹
            {

                System.out.println(array[i].getName());
                //System.out.println(array[i].getPath());
                //文件夹需要调用递归 ，深度+1
                getFile(array[i].getPath(), deep + 1);
            }
        }

    }

    public void writeUrls(String url, String outPath) throws IOException {
        File txt = new File(outPath);
        url = url + "\r\n";
        byte[] bytes = new byte[512];
        bytes = url.getBytes();
        int length = bytes.length;

        FileOutputStream fos = new FileOutputStream(txt, true);
        fos.write(bytes, 0, length);
        fos.flush();
        fos.close();
    }


    public static byte[] inputStreamToBytes(InputStream ins) {
        byte[] data = null;
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            int i = -1;
            byte[] buf = new byte[1024];
            while ((i = ins.read(buf)) != -1) {
                baos.write(buf, 0, i);
            }
            data = baos.toByteArray();
        } catch (IOException e) {
            //TODO: 错误处理

        }

        return data;
    }


    /**
     * 1、查出所有表信息
     * 2、需要修改人员表中 部门id（根据单位名称查找），职务=zw，警务通=jwth，数字电台=szdt  根据警号修改
     */
    @ApiOperation("更改人员信息")
    @GetMapping("updateTest")
    //@SysPcLog(module = "更改人员信息",operation = "修改")
    public void updateTest() {
        //修改个人信息
        List<Sheet> sheets = sheetMapper.selectList(null);
        for (Sheet sheet : sheets) {
            String dw = sheet.getDw();
            Staff staff = new Staff();
            if (StringUtils.isNotEmpty(dw)) {
                Section section = sectionMapper.selectOne(Wrappers.<Section>lambdaQuery()
                        .eq(Section::getSectionPid, 208)
                        .eq(Section::getSectionPerson, dw));
                staff.setSysSectionId(section.getSysSectionId());
            }

            staff.setStaffPost(sheet.getZw());
            staff.setStaffIdcard(sheet.getJwth());
            staff.setCellphonenumber(sheet.getJwth());
            staff.setDigitalRadio(sheet.getSzdt());

            staff.setStaffNum(sheet.getJh());
            staff.setStafftype(sheet.getZw());
            int i = staffMapper.updateByStaffNum(staff);
        }
    }

    @ApiOperation("绑定数字电台装备")
    @GetMapping("updateEquiage")
    //@SysPcLog(module = "绑定数字电台装备",operation = "新增")
    public void updateEquiage() {
        //绑定装备信息
        List<Sheet> sheets = sheetMapper.selectList(null);
        for (Sheet sheet : sheets) {
            if (!"无".equals(sheet.getSzdt()) && StringUtils.isNotEmpty(sheet.getSzdt())) {
                Equipage equipage = new Equipage();
                equipage.setGpsid(sheet.getSzdt());
                equipage.setWarningSignal(sheet.getJh());
                equipage.setDeptName("高速二支队" + sheet.getDw());
                equipage.setType("数字电台");
                equipage.setCarNo("交警" + sheet.getDw() + "-" + sheet.getXm());
                equipageMapper.insertIgnoreNull(equipage);
            }

        }
    }

    @ApiOperation("绑定警务通装备")
    @GetMapping("updateEquiageJwt")
    //@SysPcLog(module = "绑定警务通装备",operation = "新增")
    public void updateEquiageJwt() {
        //绑定装备信息
        List<Sheet> sheets = sheetMapper.selectList(null);
        for (Sheet sheet : sheets) {
            if (!"无".equals(sheet.getJwth()) && StringUtils.isNotEmpty(sheet.getJwth())) {
                Equipage equipage = new Equipage();
                equipage.setGpsid(sheet.getJwth());
                equipage.setWarningSignal(sheet.getJh());
                equipage.setDeptName("高速一支队" + sheet.getDw());
                equipage.setType("警务通");
                equipage.setCarNo(sheet.getXm() + "-" + sheet.getJwth());
                equipageMapper.insertIgnoreNull(equipage);
            }

        }
    }

    @ApiOperation("绑定辅警通装备")
    @GetMapping("updateEquiageFjt")
    //@SysPcLog(module = "绑定辅警通装备",operation = "新增")
    public void updateEquiageFjt() {
        //绑定装备信息
        List<Sheet> sheets = sheetMapper.selectList(null);
        for (Sheet sheet : sheets) {
            if (!"无".equals(sheet.getJwth()) && StringUtils.isNotEmpty(sheet.getJwth())) {
                Equipage equipage = new Equipage();
                equipage.setGpsid(sheet.getJwth());
                equipage.setWarningSignal(sheet.getJh());
                equipage.setDeptName("高速一支队" + sheet.getDw());
                equipage.setType("辅警通");
                equipage.setCarNo(sheet.getXm() + "-" + sheet.getJwth());
                equipageMapper.insertIgnoreNull(equipage);
            }

        }
    }

    @ApiOperation("修改设备人员部门")
    @GetMapping("updateEquiageBm")
    //@SysPcLog(module = "修改设备人员部门",operation = "修改设备人员部门")
    public void updateEquiageBm() {
        List<Equipage> equipages = equipageMapper.selectList(null);
        for (Equipage equipage : equipages) {
            Staff staff = staffMapper.selectStaffByNum(equipage.getWarningSignal());
            if (staff != null) {
                equipage.setDeptName(staff.getSectionName());
                equipageMapper.updateById(equipage);
            }


        }


    }


}
